import { SocketManager } from './socket.js'

/**
 * TradingView API管理类 - 连接到WebSocket后端服务
 */
export class TradingViewApi {
  constructor(options = {}) {
    this.options = {
      wsUrl: 'ws://localhost:8080',
      symbol: 'ethusdt',
      interval: '5',
      ...options
    }

    this.symbol = this.options.symbol
    this.interval = this.options.interval
    this.cacheData = {}
    this.lastTime = null
    this.isLoading = false
    this.socket = null

    // 事件回调
    this.onPriceUpdate = null
    this.onConnectionStatus = null
    this.onHistoricalData = null
    this.onRealtimeUpdate = null

    // 初始化WebSocket连接
    this.initWebSocket()
  }

  /**
   * 初始化WebSocket连接
   */
  initWebSocket() {
    try {
      this.socket = new SocketManager(this.options.wsUrl)
      this.setupSocketEvents()
      this.socket.doOpen()
    } catch (error) {
      console.error('WebSocket初始化失败:', error)
      this.emitConnectionStatus('error')
    }
  }

  /**
   * 设置WebSocket事件监听
   */
  setupSocketEvents() {
    this.socket.on('open', () => {
      console.log('TradingView WebSocket连接已建立')
      this.emitConnectionStatus('connected')
      
      // 请求历史数据
      this.requestHistoricalData(this.symbol, this.interval)
      
      // 订阅实时数据
      this.subscribeRealTimeData(this.symbol, this.interval)
    })

    this.socket.on('close', () => {
      console.log('TradingView WebSocket连接已关闭')
      this.emitConnectionStatus('disconnected')
    })

    this.socket.on('error', (error) => {
      console.error('TradingView WebSocket错误:', error)
      this.emitConnectionStatus('error')
    })

    this.socket.on('message', (data) => {
      this.handleWebSocketMessage(data)
    })
  }

  /**
   * 处理WebSocket消息
   */
  handleWebSocketMessage(data) {
    try {
      if (!data) return

      // 处理历史数据响应
      if (data.type === 'history' && data.data) {
        this.processHistoricalData(data)
      }
      
      // 处理实时数据更新
      else if (data.type && data.type.includes('candle')) {
        this.processRealTimeData(data)
      }
      
      // 处理价格更新
      else if (data.type === 'price' && data.data) {
        this.processPriceUpdate(data)
      }

    } catch (error) {
      console.error('处理WebSocket消息失败:', error)
    }
  }

  /**
   * 处理历史数据
   */
  processHistoricalData(message) {
    const { symbol, interval, data } = message
    const ticker = `${symbol}-${interval}`
    
    if (!data || !Array.isArray(data)) return

    // 转换数据格式为TradingView格式
    const formattedData = data.map(item => ({
      time: Math.floor(item.timestamp / 1000), // 转换为秒级时间戳
      open: parseFloat(item.open),
      high: parseFloat(item.high),
      low: parseFloat(item.low),
      close: parseFloat(item.close),
      volume: parseInt(item.quote_vol || 0)
    })).sort((a, b) => a.time - b.time) // 按时间排序

    this.cacheData[ticker] = formattedData
    if (formattedData.length > 0) {
      this.lastTime = formattedData[formattedData.length - 1].time
    }

    console.log(`接收到 ${symbol} ${interval} 历史数据 ${formattedData.length} 条`)

    // 触发历史数据回调
    if (this.onHistoricalData) {
      this.onHistoricalData(formattedData)
    }
  }

  /**
   * 处理实时K线数据
   */
  processRealTimeData(message) {
    // 解析频道信息：candle.M5.ethusdt -> symbol: ethusdt, interval: 5
    const parts = message.type.split('.')
    if (parts.length < 3) return
    
    const interval = parts[1].replace('M', '')
    const symbol = parts[2]
    const ticker = `${symbol}-${interval}`
    
    console.log(`收到 ${symbol} ${interval} 实时K线数据:`, message)
    
    // 转换数据格式
    const newBar = {
      time: Math.floor(message.timestamp / 1000) || message.id,
      open: parseFloat(message.open),
      high: parseFloat(message.high),
      low: parseFloat(message.low),
      close: parseFloat(message.close),
      volume: parseInt(message.quote_vol || 0)
    }

    // 检查必须字段是否有效
    if (isNaN(newBar.open) || isNaN(newBar.high) || isNaN(newBar.low) || isNaN(newBar.close)) {
      console.error('实时K线数据格式无效:', message)
      return
    }

    // 更新缓存数据
    if (!this.cacheData[ticker]) {
      this.cacheData[ticker] = []
    }
    
    const lastIndex = this.cacheData[ticker].length - 1
    if (lastIndex >= 0) {
      // 如果是同一时间段，更新最后一条数据
      if (this.cacheData[ticker][lastIndex].time === newBar.time) {
        this.cacheData[ticker][lastIndex] = newBar
      } else {
        // 否则添加新数据
        this.cacheData[ticker].push(newBar)
      }
    } else {
      this.cacheData[ticker].push(newBar)
    }

    console.log(`更新 ${symbol} ${interval} 实时K线数据:`, newBar)

    // 触发实时更新回调
    if (this.onRealtimeUpdate) {
      this.onRealtimeUpdate(newBar)
    }
  }

  /**
   * 处理价格更新
   */
  processPriceUpdate(message) {
    const { symbol, data } = message
    
    if (!data) return

    // 触发价格更新回调
    if (this.onPriceUpdate) {
      this.onPriceUpdate({
        symbol: symbol,
        price: parseFloat(data.price),
        change: parseFloat(data.change || 0),
        changePercent: parseFloat(data.changePercent || 0),
        time: Math.floor((data.timestamp || Date.now()) / 1000)
      })
    }
  }

  /**
   * 请求历史数据
   */
  requestHistoricalData(symbol, interval) {
    if (!this.socket || !this.socket.checkOpen()) {
      console.warn('WebSocket未连接，无法请求历史数据')
      return
    }

    // 格式化订阅周期（处理特殊格式）
    const formattedInterval = this.formatInterval(interval)

    // 根据服务器端格式修改请求格式
    const message = {
      cmd: 'req',
      args: [`candle.M${formattedInterval}.${symbol}`, 200, Math.floor(Date.now() / 1000)]
    }

    this.socket.send(message)
    console.log('请求历史数据:', message)
  }

  /**
   * 订阅实时数据
   */
  subscribeRealTimeData(symbol, interval) {
    if (!this.socket || !this.socket.checkOpen()) {
      console.warn('WebSocket未连接，无法订阅实时数据')
      return
    }

    // 格式化订阅周期（处理特殊格式）
    const formattedInterval = this.formatInterval(interval)

    // 根据服务器端格式修改请求格式
    const message = {
      cmd: 'sub',
      args: [`candle.M${formattedInterval}.${symbol}`]
    }

    this.socket.send(message)
    console.log('订阅实时数据:', message)
  }

  /**
   * 取消订阅
   */
  unsubscribeRealTimeData(symbol, interval) {
    if (!this.socket || !this.socket.checkOpen()) return

    // 格式化订阅周期（处理特殊格式）
    const formattedInterval = this.formatInterval(interval)

    const message = {
      cmd: 'unsub',
      args: [`candle.M${formattedInterval}.${symbol}`]
    }

    this.socket.send(message)
    console.log('取消订阅实时数据:', message)
  }

  /**
   * 格式化时间周期
   */
  formatInterval(interval) {
    // 处理日线、周线、月线的特殊格式
    if (interval === '1D' || interval === 'D') {
      return 'D'
    } else if (interval === '1W' || interval === 'W') {
      return 'W'
    } else if (interval === '1M' || interval === 'M') {
      return 'M'
    }
    return interval
  }

  /**
   * 获取K线数据 (TradingView datafeed接口)
   */
  getBars(symbolInfo, resolution, rangeStartDate, rangeEndDate, onLoadedCallback) {
    const ticker = `${symbolInfo.name}-${resolution}`
    
    // 如果没有缓存数据，请求数据
    if (!this.cacheData[ticker]) {
      this.requestHistoricalData(symbolInfo.name, resolution)
      
      // 等待数据加载
      const checkData = () => {
        if (this.cacheData[ticker]) {
          this.filterAndReturnBars(ticker, rangeStartDate, rangeEndDate, onLoadedCallback)
        } else {
          setTimeout(checkData, 100)
        }
      }
      setTimeout(checkData, 100)
      return
    }

    this.filterAndReturnBars(ticker, rangeStartDate, rangeEndDate, onLoadedCallback)
  }

  /**
   * 过滤并返回K线数据
   */
  filterAndReturnBars(ticker, rangeStartDate, rangeEndDate, onLoadedCallback) {
    let data = this.cacheData[ticker] || []
    
    // 根据时间范围过滤数据
    if (rangeStartDate && rangeEndDate) {
      data = data.filter(bar => {
        return bar.time >= rangeStartDate && bar.time <= rangeEndDate
      })
    }
    
    console.log(`返回 ${data.length} 条K线数据 (${ticker})`)
    
    // 异步返回数据
    setTimeout(() => {
      onLoadedCallback(data)
    }, 10)
  }

  /**
   * 切换股票符号
   */
  changeSymbol(newSymbol) {
    if (newSymbol === this.symbol) return

    console.log(`切换交易对: ${this.symbol} -> ${newSymbol}`)

    // 取消当前订阅
    this.unsubscribeRealTimeData(this.symbol, this.interval)
    
    // 更新符号
    this.symbol = newSymbol
    
    // 请求新符号的数据
    this.requestHistoricalData(newSymbol, this.interval)
    this.subscribeRealTimeData(newSymbol, this.interval)
  }

  /**
   * 切换时间周期
   */
  changeInterval(newInterval) {
    if (newInterval === this.interval) return

    console.log(`切换时间周期: ${this.interval} -> ${newInterval}`)

    // 取消当前订阅
    this.unsubscribeRealTimeData(this.symbol, this.interval)
    
    // 更新时间周期
    this.interval = newInterval
    
    // 请求新时间周期的数据
    this.requestHistoricalData(this.symbol, newInterval)
    this.subscribeRealTimeData(this.symbol, newInterval)
  }

  /**
   * 设置价格更新回调
   */
  setPriceUpdateCallback(callback) {
    this.onPriceUpdate = callback
  }

  /**
   * 设置连接状态回调
   */
  setConnectionStatusCallback(callback) {
    this.onConnectionStatus = callback
  }

  /**
   * 触发连接状态事件
   */
  emitConnectionStatus(status) {
    if (this.onConnectionStatus) {
      this.onConnectionStatus(status)
    }
  }

  /**
   * 销毁API实例
   */
  destroy() {
    // 取消订阅
    if (this.symbol && this.interval) {
      this.unsubscribeRealTimeData(this.symbol, this.interval)
    }
    
    // 关闭WebSocket连接
    if (this.socket) {
      this.socket.destroy()
      this.socket = null
    }
    
    // 清理数据
    this.cacheData = {}
    this.onPriceUpdate = null
    this.onConnectionStatus = null
    this.onHistoricalData = null
    this.onRealtimeUpdate = null
  }
}